package com.etop.weibo.filter;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;


public class LoginFilter implements Filter {
	FilterConfig cfg;
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest hrequest = (HttpServletRequest) request;
		HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(
				(HttpServletResponse) response);

		String redirectPath = hrequest.getContextPath() + "/" + cfg.getInitParameter("redirectPath");
		String notWork = cfg.getInitParameter("notWork");
		
		//过滤器不工作
		if(notWork.equals("true")){
			chain.doFilter(request, response);
			return;
		}

		//检测是否登录
		if(hrequest.getSession().getAttribute("user") == null){
			wrapper.sendRedirect(redirectPath);
			return;
		} else {
			chain.doFilter(request, response);
			return;
		}
	}
	@Override
	public void init(FilterConfig cfg) throws ServletException {
		this.cfg = cfg;
	}
}
